import { Select } from "antd"
import PropTypes from "prop-types"

// inputSelect onChange方法与某个flowable依赖库有冲突
const InputSelect = ({
  setter,
  getter,
  ...props
}) => {

  let value
  if (getter) {
    value = getter(props.value)
  } else {
    value = props.value
  }

  const handleChange = (value) => {
    if (setter) {
      props.onChange(setter(value))
    } else {
      props.onChange(value)
    }
  }

  return <Select
    mode={props.multiple ? 'multiple' : undefined}
    {...props}
    onChange={() => { }}
    value={value}
    onDeselect={(val) => {
      handleChange(props.value.filter(el => el !== val))
    }}
    onClear={() => {
      handleChange(undefined)
    }}
    onSelect={(val) => {
      if (!props.multiple) {
        handleChange(val)
      } else {
        let newValue = []
        if (!props.value || props.value.length === 0) {
          newValue = [val]
        } else {
          if (props.value.includes(val)) {
            newValue = props.value.filter(el => el !== val)
          } else {
            newValue = props.value.concat([val])
          }
        }
        handleChange(newValue)
      }
    }}
  ></Select>
}

InputSelect.propTypes = {
  setter: PropTypes.func,
  getter: PropTypes.func
}

InputSelect.propsMap = [
  {
    type: 'selectOptions',
    name: 'options',
    label: '选项'
  },
  {
    type: 'boolean',
    name: 'multiple',
    label: '是否多选'
  }
]

export default InputSelect